#!/usr/bin/env bash
RAILS_ENV=production
cd "/home/chenpo/workspace/rails_blog_demo"
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
  # First try to load from a user install
  source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
  # Then try to load from a root install
  source "/usr/local/rvm/scripts/rvm"
else
  echo "ERROR: An RVM installation was not found.\n"
fi
rvm use 1.9.3
branch=master
sidekiq_pid_file="tmp/pids/sidekiq.pid"

git checkout $branch

log ()
{
  echo "***** ${FUNCNAME[1]}"
}

gitdiff()
{
  log
  git fetch
  newfiles=$(git diff --name-only HEAD origin/$branch)
}

newgem()
{
  log
  bundle install --without development test --deployment
}

migrate()
{
  log
  bundle exec rake db:migrate RAILS_ENV=$RAILS_ENV
}

assets()
{
#  bundle exec rake assets:clean RAILS_ENV=$RAILS_ENV
  log
  bundle exec rake assets:precompile RAILS_ENV=$RAILS_ENV
}

start_unicorn()
{
  log
  bundle exec unicorn -c $(pwd)/config/unicorn.rb -E $RAILS_ENV -D
}

stop_unicorn()
{
  log
  kill -QUIT $(cat log/unicorn.pid)
}

reload_unicorn()
{
  log
  kill -HUP $(cat log/unicorn.pid)
}

quiet_sidekiq()
{
  log
  [ -s $sidekiq_pid_file ] && RAILS_ENV=$RAILS_ENV bundle exec sidekiqctl quiet $sidekiq_pid_file
}

stop_sidekiq()
{
  log
  [ -s $sidekiq_pid_file ] && RAILS_ENV=$RAILS_ENV bundle exec sidekiqctl stop $sidekiq_pid_file
}

start_sidekiq()
{
  log
  nohup bundle exec sidekiq -e $RAILS_ENV -C config/sidekiq.yml &
}

case $1 in
  "all")
    gitdiff
    if [ `echo "$newfiles" | wc -l` -gt 0 ]; then
      quiet_sidekiq
      git pull

      if [ $(echo "$newfiles" | grep -c "db/migrate/") -gt 0 ];then
        migrate
      fi

      if [ $(echo "$newfiles" | grep -c "app/assets/") -gt 0 ];then
        assets
      fi

      if [ $(echo "$newfiles" | grep -c "Gemfile") -gt 0 ]; then
        newgem
        stop_unicorn
        sleep 2
        start_unicorn
      else
        reload_unicorn
      fi

      stop_sidekiq
      start_sidekiq
    fi
  ;;
  "start")
     start_unicorn
     start_sidekiq
  ;;
  "stop")
     quiet_sidekiq
     stop_unicorn
     stop_sidekiq
  ;;
  "reload")
     quiet_sidekiq
     reload_unicorn
     stop_sidekiq
     start_sidekiq
  ;;
  "newgem")
     quiet_sidekiq
     newgem
     stop_unicorn
     sleep 2
     start_unicorn
     stop_sidekiq
     start_sidekiq
  ;;
  "migrate")
     quiet_sidekiq
     migrate
     reload_unicorn
     stop_sidekiq
     start_sidekiq
  ;;
  "assets")
     quiet_sidekiq
     assets
     reload_unicorn
     stop_sidekiq
     start_sidekiq
  ;;
  *)
     echo $"Usage: $0 {all|start|stop|reload|newgem|migrate|assets}"
     exit 2
esac

